package com.chen.project.file_server;


import com.chen.project.file_server.servlet.FileServlet;
import com.chen.project.file_server.utils.JDBCUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class FileServer {

    public static void main(String[] args) throws Exception {

        // 创建 jetty 实例
        Server server = new Server(8888);

        // 配置 jetty 处理器
        ServletContextHandler sch = new ServletContextHandler(server, "/");
        server.setHandler(sch);

        // 添加 servlet
        sch.addServlet(FileServlet.class, "/file");

        // 启动服务器前，确认库中有 file_info 表
        genFileInfoTable();

        // 启动 jetty
        server.start();
        server.join();
    }

    /**
     * 如果数据库中没有 file_info表，就创建
     */
    private static void genFileInfoTable() {

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            String testSql = "select * from file_info";
            ps = conn.prepareStatement(testSql);
            ps.execute();
        } catch (SQLException throwables) {

            System.out.println("file_info表不存在");
            String createSql = "CREATE TABLE file_info (id int GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) primary key," +
                    "file_ori_name VARCHAR ( 100 )," +
                    "file_size BIGINT," +
                    "file_type VARCHAR ( 10 ) ," +
                    "create_time timestamp ," +
                    "save_path VARCHAR ( 100 ) ," +
                    "envelope VARCHAR ( 200 ) ," +
                    "uuid varchar(50) unique )";
            try {
                ps = conn.prepareStatement(createSql);
                ps.execute();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
    }
}
